<template>
  <div>
  <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图 -->
      <el-card class="box-card">
        <!-- 警告区域 -->
        <el-alert
          title="添加商品信息"
          :closable="false"
          type="info"
          center
          show-icon>
        </el-alert>
        <!-- 步骤条 -->
        <el-steps align-center :space="200" :active="activeTabs - 0" finish-status="success">
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <!-- tabs标签页 -->
        <el-form :rules="addGoodsFormRules" label-position="top" ref="addGoodsFormRef" :model="addGoodsForm"
        label-width="80px">
          <el-tabs @tab-click="tabsClick" :before-leave="beforeLeave" v-model="activeTabs" tab-position="left">
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addGoodsForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item type="numble" label="商品价格" prop="goods_price">
                <el-input v-model="addGoodsForm.goods_price"></el-input>
              </el-form-item>
              <el-form-item type="numble" label="商品数量" prop="goods_number">
                <el-input v-model="addGoodsForm.goods_number"></el-input>
              </el-form-item>
              <el-form-item type="numble" label="商品重量" prop="goods_weight">
                <el-input v-model="addGoodsForm.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_numble">
                <!-- Cascader 级联选择器 -->
                <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cates"
                :props="cascaderProps"
                >
                </el-cascader>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
              <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox border v-for="(checkboxItem, index) in item.attr_vals" :key="index" :label="checkboxItem">
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
              <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <!-- action：请求的接口地址，写完整的接口地址，Axios对该组件不起作用
              ：on-preview 点击预览的回调函数
              ：on-remove 点击移除图片的回调函数
              list-type： 上传图片后的类型 -->
              <el-upload
                class="upload-demo"
                action="https://www.liulongbin.top:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :headers="uploadHeaders"
                :on-success="uploadOnSuccess"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <quill-editor></quill-editor>
              <el-button style="margin-top: 15px" type="primary" @click="addGoods">添加商品</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-card>
      <!-- 点击预览图片的对话框 -->
      <el-dialog
        title="预览图片"
        :visible.sync="previewImgDialogVisible"
        width="50%">
        <img style="width: 100%" :src="imgUrl" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="previewImgDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="previewImgDialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>

  </div>
</template>

<script>

export default {
  data () {
    return {
      activeTabs: 0,
      addGoodsForm: {
        goods_name: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_cat: [2273, 2274, 2275],
        // 图片
        pics: []
      },
      // 级联选择器的所有数据
      cates: [],
      // 商品参数
      manyData: [],
      // 商品属性
      onlyData: [],
      // 上传图片请求头token
      uploadHeaders: {
        Authorization: sessionStorage.getItem('token')
      },
      // 校验表达式数据
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      },
      // 级联选择器双向绑定
      cascaderValue: [],
      cascaderProps: {
        label: 'cat_name',
        expandTrigger: 'hover',
        value: 'cat_id'
      },
      previewImgDialogVisible: false,
      imgUrl: ''
    }
  },

  created () {
    this.getGoodsCate()
  },
  computed: {
    cateId () {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      // step1获取
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      // step 2赋值
      this.cates = res.data
    },
    // 只有离开某一标签页即触发的事件
    beforeLeave (activeName, oldActiveName) {
      // activeName: 进入的tab标签
      // oldActiveName 离开的tab标签name
      console.log('离开了', activeName, oldActiveName)
      if (oldActiveName === '0') {
        if (this.addGoodsForm.goods_cat.length !== 3) {
          this.$message.error('请选择三级商品分类')
          // 阻止离开
          return false
        }
      }
    },
    // 点击tabs标签页触发的事件
    async tabsClick () {
      // 进入了商品动态参数
      // console.log('点击了商品参数')
      if (this.activeTabs === '1') {
        const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('获取失败')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })
        this.manyData = res.data
      } else if (this.activeTabs === '2') {
        // 进入了商品属性
        const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取失败')
        this.onlyData = res.data
      }
    },
    // 点击预览
    handlePreview (file) {
      console.log(file.response.data.url)
      this.imgUrl = file.response.data.url
      this.previewImgDialogVisible = true
    },
    // 点击移除图片
    handleRemove (file) {
      // 点击删除当前的图片临时路径
      const filePath = file.response.data.tmp_path
      // 通过findindex查找到要删除这一项的索引
      const index = this.addGoodsForm.pics.findIndex(item => {
        return item.pic === filePath
      })
      // 通过索引进行删除
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 上传成功的回调函数
    uploadOnSuccess (res) {
      console.log('上传成功的钩子')
      this.addGoodsForm.pics.push({
        pic: res.data.tmp_path
      })
    },
    // 点击添加商品
    addGoods () {
      this.$refs.addGoodsFormRef.validate(async flag => {
        if (!flag) return this.$message.error('亲，请完善基本信息项为填写')
        // this.addGoodsForm 用来控制页面
        // addGoodsForm： 交给后台
        // 实现深拷贝 JSON。parse（JSON.stringify（this.addGoodsForm))
        const addGoodsForm = this.cloneDeep(this.addGoodsForm)
        // const addGoodsForm = JSON.parse(JSON.stringify(this.addGoodsForm))
        addGoodsForm.goods_cat = addGoodsForm.goods_cat.join(' ')
        console.log(addGoodsForm, this.addGoodsForm)
        // attrs用来传递所有动态参数和静态属性
        addGoodsForm.attrs = []
        this.manyData.forEach(item => {
          addGoodsForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        this.onlyData.forEach(item => {
          addGoodsForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        // 发送请求完成添加
        const { data: res } = await this.$axios.post('goods', addGoodsForm)
        if (res.meta.status !== 201) return this.$message.error('创建商品失败')
        this.$message.success('创建商品成功')
        this.$router.push('/goods')
        console.log(res)
      })
    }
  }
}
</script>

<style scoped lang='less'>
  .el-checkbox {
    margin-right: 0;
  }
</style>
